<template>
  <div class="tp" v-loading="state.loading">
    <Header />

    <Content>
      <div class="cp">
        <div class="card">
          <BasicTable @register="registerTable" :resizeHeightOffset="44">
            <template #tableTitle>
              <a-flex gap="middle" align="center">
                <a-button type="primary" @click="onIn">商品入库</a-button>
                <a-button type="primary" @click="onOut">商品出库</a-button>
                <a-button type="primary" @click="onExportExcel">导出Excel</a-button>
                <a-button type="primary" @click="onCheck">库存校正</a-button>
              </a-flex>
            </template>
            <template #toolbar>
              <a-flex gap="middle" align="center" justify="flex-end">
                <a-button type="link" @click="onReview"
                  >盘点记录
                  <template #icon>
                    <FileTextOutlined />
                  </template>
                </a-button>
              </a-flex>
            </template>
            <template #status="{ record }">
              <a-flex gap="small" align="center" class="f-tag-status">
                <div
                  class="f-tag-backgroundColor"
                  :style="`background-color:${record.status === 1 ? '#31b89a' : '#f24427'};`"
                  >&nbsp;</div
                >
                <div>{{ getLabel(stockStatus, record.status) }}</div>
              </a-flex>
            </template>
            <template #action="{ record }">
              <TableAction
                :divider="true"
                :actions="[
                  {
                    color: 'success',
                    label: '出库',
                    onClick: () => onOut2(record),
                  },
                  {
                    color: 'success',
                    label: '详情',
                    onClick: () => onMore(record),
                  },
                ]"
              />
            </template>
          </BasicTable>
        </div>
      </div>
    </Content>
  </div>
</template>

<script setup>
  import { defineOptions, h, reactive, ref } from 'vue';

  import { BasicTable, TableAction, useTable } from '@/components/Table';

  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import { PAGE, POST, POST_API } from '@/api/http';
  import { getLabel, stockStatus } from '@/api/ds';
  import { useMessage } from '@/hooks/web/useMessage';

  import { FileTextOutlined } from '@ant-design/icons-vue';
  import ProImgCell from '@/widget/pro-img-cell.vue';

  import { useRouter } from 'vue-router';
  import { downloadByData } from '@/utils/file/download';

  defineOptions({ name: 'StockList' });

  const router = useRouter();
  const { createMessage } = useMessage();
  const cateParams = ref({ cateType: 'P', cateSubName: null });
  const state = reactive({ loading: false });

  const [registerTable, { getForm }] = useTable({
    api: PAGE('/product/getStockInfo'),
    beforeFetch: (arg) => {
      const { field, order } = arg;
      const rank = order === 'descend' ? 'desc' : 'asc';

      if (field === 'lastSyncStock') {
        arg.orderByValue = `last_sync_stock ${rank}`;
      }

      return arg;
    },
    formConfig: {
      baseColProps: { style: { paddingRight: '12px' } },
      actionColOptions: { span: 10 },
      schemas: [
        {
          field: 'goodsName',
          component: 'Input',
          componentProps: {
            placeholder: ' 输入商品名称搜索',
          },
          colProps: { span: 6 },
        },

        {
          field: 'thirdCateCodeList',
          component: 'ApiSelect',

          componentProps: {
            placeholder: '商品分类',
            valueField: 'cateCode',
            labelField: 'cateSubName',
            mode: 'multiple',
            showArrow: true,
            showSearch: false,
            filterOption: false,
            api: POST_API('/product/libCategoryStoreListAll'),
            params: cateParams,
            onSearch: (value) => {
              cateParams.value.cateSubName = value;
            },
          },

          colProps: { span: 4 },
        },

        {
          field: 'statusList',
          component: 'Select',
          componentProps: {
            mode: 'multiple',
            showArrow: true,
            placeholder: '状态',
            showSearch: false,
            options: stockStatus,
          },
          colProps: { span: 4 },
        },
      ],
    },
    columns: [
      {
        title: '商品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
        width: 290,
        customRender: ({ value: title, record }) =>
          h(ProImgCell, { src: record.goodsImage, title }),
      },

      {
        title: '商品分类',
        dataIndex: 'libCategoryName',
        ellipsis: false,
      },
      {
        title: '规格',
        dataIndex: 'specs',
        ellipsis: false,
      },

      {
        title: '库存数量',
        dataIndex: 'lastSyncStock',
        ellipsis: false,
        sorter: true,
        customRender: ({ value, record }) => `${value || '0'}${record.saleUnit}`,
      },

      {
        title: '状态',
        dataIndex: 'status',
        ellipsis: false,
        // customRender: ({ value }) => getLabel(stockStatus, value),
        slots: { customRender: 'status' },
      },
    ],
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    pagination: { hideOnSinglePage: false },
    actionColumn: {
      title: '操作',
      align: 'center',
      width: 160,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  function onIn() {
    router.push(`/stock/list/in?stockType=O`);
  }

  function onOut() {
    router.push(`/stock/list/out?stockType=O`);
  }

  function onReview() {
    router.push(`/stock/list/review?stockType=O`);
  }

  function onOut2({ goodsSn }) {
    router.push(`/stock/list/out2?stockType=O&goodsSn=${goodsSn}`);
  }

  function onMore({ goodsSn }) {
    router.push(`/stock/list/detail?goodsSn=${goodsSn}`);
  }

  async function onExportExcel() {
    const data = getForm().getFieldsValue();

    try {
      try {
        state.loading = true;
        const res = await POST(
          '/product/exportStockInfo',
          data,
          { isReturnNativeResponse: true },
          { responseType: 'arraybuffer' },
        );
        const filename = res.headers['content-disposition'].split('filename=')[1];
        downloadByData(res.data, decodeURI(filename), 'application/vnd.ms-excel');
      } finally {
        state.loading = false;
      }
    } catch (e) {
      createMessage.error(e.message);
    }
  }

  function onCheck() {
    router.push(`/stock/list/check?stockType=O`);
  }
</script>
<style lang="less" scoped>
  .card {
    padding: 12px;
  }

  .f-tag-status {
    display: flex;
    justify-content: center;
  }
  .f-tag-backgroundColor {
    width: 6px;
    height: 6px;
    border-radius: 50px;
  }
</style>
